package com.zero.config;

import com.zero.entity.Admin;
import com.zero.entity.FamilyMember;
import com.zero.entity.Web;
import com.zero.mapper.WebMapper;
import com.zero.service.WebService;
import com.zero.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token拦截器
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的token
        String token = request.getHeader(JWTUtil.token);

        if (JWTUtil.getType(token).equals("ADMIN")){
            //根据token解析出请求的用户信息
            Admin admin = JWTUtil.getAdmin(token);

            //token不合法时抛出异常
            if(admin == null){
                throw new RuntimeException("token超时或不合法");
            }

            //重新生成新的token
            String newToken = JWTUtil.sign(admin);

            //将新的token设置到响应头中
            response.setHeader(JWTUtil.token, newToken);

            //将token信息暴露给客户端（必须）
            response.setHeader("Access-Control-Expose-Headers", JWTUtil.token);

            //向请求中设置用户信息，以便接下来使用
            request.setAttribute("admin", admin);
        }else if (JWTUtil.getType(token).equals("FAMILY_MEMBER")){
            FamilyMember familyMember = JWTUtil.getFamilyMember(token);
            if (familyMember == null)
                throw new RuntimeException("token超时或不合法");

            //生成新的token
            String newToken = JWTUtil.sign(familyMember);

            //将新的token设置到响应头中
            response.setHeader(JWTUtil.token, newToken);

            //将token信息暴露给客户端（必须）
            response.setHeader("Access-Control-Expose-Headers", JWTUtil.token);

            //向请求中设置用户信息，以便接下来使用
            request.setAttribute("familyMember", familyMember);
        }

        return true;
    }
}
